#include <iostream>

// 定义一些常量
const int TRUE = 1;
const int FALSE = 0;
const int OK = 1;
const int ERROR = 0;
const int OVERFLOW = -1;

// 类型定义
using Status = int;
using ElemType = int;

// 测试程序长度定义
const int LENGTH = 5;

// 链表节点类
struct LNode {
    ElemType data;
    LNode* next;

    // 构造函数
    LNode(ElemType d, LNode* n = nullptr) : data(d), next(n) {}
};

// 链表类
class LinkList {
public:
    LinkList() : head(nullptr) {}

    // 创建包含 n 个元素的链表，元素值存储在 data 数组中
    Status create(const ElemType* data, int n) {
        if (n < 0) return ERROR;

        LNode* p = nullptr;
        for (int i = 0; i < n; i++) {
            LNode* q = new LNode(data[i]);
            if (q == nullptr) return OVERFLOW;
            if (head == nullptr) head = q;
            else p->next = q;
            p = q;
        }
        return OK;
    }

    // 从链表末尾入链表
    Status EnQueue(ElemType e) {
        LNode* q = new LNode(e);
        if (q == nullptr) return OVERFLOW;

        if (head == nullptr) {
            head = q;
        } else {
            LNode* p = head;
            while (p->next != nullptr) {
                p = p->next;
            }
            p->next = q;
        }
        return OK;
    }

    // 从链表头节点出链表
    Status DeQueue(ElemType& e) {
        if (head == nullptr) return ERROR;

        LNode* p = head;
        e = p->data;
        head = head->next;
        delete p;
        return OK;
    }

    // 遍历单链表并调用访问函数
    void ListTraverse(Status(*visit)(ElemType e)) const {
        if (head == nullptr) return;
        LNode* p = head;
        while (p != nullptr) {
            visit(p->data);
            p = p->next;
        }
    }

private:
    LNode* head; // 链表头指针
};

// 访问函数
Status visit(ElemType e) {
    std::cout << e << "\t";
    return OK;
}

int main() {
    ElemType e, data[LENGTH] = { 1, 2, 3, 4, 5 };
    LinkList L;

    // 显示测试值
    std::cout << "---【单链表】---" << std::endl;
    std::cout << "待测试元素为：" << std::endl;
    for (int i = 0; i < LENGTH; i++) std::cout << data[i] << "\t";
    std::cout << std::endl;

    // 创建链表L
    std::cout << "创建链表L" << std::endl;
    if (ERROR == L.create(data, LENGTH)) {
        std::cout << "创建链表L失败" << std::endl;
        return -1;
    }
    std::cout << "成功创建包含" << LENGTH << "个元素的链表L" << std::endl;

    // 遍历单链表
    std::cout << "此时链表中元素为：" << std::endl;
    L.ListTraverse(visit);
    std::cout << std::endl;

    // 从链表头节点出链表到e
    std::cout << "出链表到e" << std::endl;
    L.DeQueue(e);
    std::cout << "出链表的元素为：" << e << std::endl;
    std::cout << "此时链表中元素为：" << std::endl;
    L.ListTraverse(visit);
    std::cout << std::endl;

    // e从链表末尾入链表
    std::cout << "e入链表" << std::endl;
    L.EnQueue(e);
    std::cout << "入链表的元素为：" << e << std::endl;
    std::cout << "此时链表中元素为：" << std::endl;
    L.ListTraverse(visit);
    std::cout << std::endl;

    return 0;
}
